#include "ping_service.h"
#include "framework/service_server.h"
#include "framework/service_registry.h"
#include "database/mysql_pool.h"
#include "database/redis_pool.h"
#include "logger/LoggerManager.h"
#include <iostream>
#include <csignal>
#include <atomic>
#include <thread>
#include <chrono>
#include <unistd.h>

using namespace cpp_backend;

// 全局运行标志
std::atomic<bool> g_running{true};

// 信号处理
void signal_handler(int signal) {
    if (signal == SIGTERM || signal == SIGINT) {
        std::cout << "\n[Signal] Received shutdown signal" << std::endl;
        g_running = false;
    }
}

int main(int argc, char* argv[]) {
    std::cout << "========================================" << std::endl;
    std::cout << "  PingService - Microservice Process" << std::endl;
    std::cout << "========================================" << std::endl;
    
    try {
        std::cout << "[DEBUG] Entering try block..." << std::endl;
        
        // ========================================
        // 1. 解析配置
        // ========================================
        std::cout << "\n[Step 1] Loading configuration..." << std::endl;
        
        std::string host = "0.0.0.0";
        int port = 9003;  // PingService默认端口
        
        // 从命令行参数读取端口（可选）
        if (argc > 1) {
            port = std::atoi(argv[1]);
        }
        
        std::string instance_id = "ping-service-" + std::to_string(getpid());
        
        std::cout << "  Host: " << host << std::endl;
        std::cout << "  Port: " << port << std::endl;
        std::cout << "  Instance ID: " << instance_id << std::endl;
        
        // ========================================
        // 2. 初始化基础组件（复用现有代码）
        // ========================================
        std::cout << "\n[Step 2] Initializing infrastructure..." << std::endl;
        
        // Redis连接池（用于服务注册）
        auto& redis_pool = cpp_backend::database::RedisPool::Instance();
        if (!redis_pool.Initialize()) {
            std::cerr << "❌ Failed to initialize Redis pool" << std::endl;
            return 1;
        }
        std::cout << "  ✓ Redis Pool initialized" << std::endl;
        
        // 日志系统（可选）
        logger::LogConfig log_config;
        log_config.moduleName = "PingService";
        auto& logger = logger::LoggerManager::getInstance();
        logger.init(log_config);
        std::cout << "  ✓ Logger initialized" << std::endl;
        
        // ========================================
        // 3. 创建业务服务（复用PingService）
        // ========================================
        std::cout << "\n[Step 3] Creating PingService..." << std::endl;
        std::cout << "[DEBUG] Creating PingService object..." << std::endl;
        
        auto ping_service = std::make_shared<services::PingService>();
        std::cout << "[DEBUG] PingService object created" << std::endl;
        
        std::cout << "[DEBUG] Calling Initialize()..." << std::endl;
        if (!ping_service->Initialize()) {
            std::cerr << "❌ Failed to initialize PingService" << std::endl;
            return 1;
        }
        std::cout << "[DEBUG] Initialize() completed" << std::endl;
        
        std::cout << "[DEBUG] Calling Start()..." << std::endl;
        if (!ping_service->Start()) {
            std::cerr << "❌ Failed to start PingService" << std::endl;
            return 1;
        }
        std::cout << "[DEBUG] Start() completed" << std::endl;
        
        std::cout << "  ✓ PingService created and started" << std::endl;
        std::cout << "    Name: " << ping_service->GetServiceName() << std::endl;
        std::cout << "    Version: " << ping_service->GetServiceVersion() << std::endl;
        
        // ========================================
        // 4. 创建gRPC服务器
        // ========================================
        std::cout << "\n[Step 4] Creating gRPC server..." << std::endl;
        
        framework::ServiceServer server(port);
        server.register_service(ping_service.get());
        
        if (!server.start()) {
            std::cerr << "❌ Failed to start gRPC server" << std::endl;
            return 1;
        }
        std::cout << "  ✓ gRPC server started on port " << port << std::endl;
        
        // ========================================
        // 5. 注册到服务中心
        // ========================================
        std::cout << "\n[Step 5] Registering to service registry..." << std::endl;
        
        framework::ServiceRegistry registry(&redis_pool);
        framework::ServiceInstance instance;
        instance.service_name = ping_service->GetServiceName();
        instance.host = host;
        instance.port = port;
        instance.instance_id = instance_id;
        instance.weight = 10;
        instance.register_time = std::chrono::system_clock::now().time_since_epoch().count();
        
        if (!registry.register_service(instance)) {
            std::cerr << "❌ Failed to register service" << std::endl;
            return 1;
        }
        std::cout << "  ✓ Service registered: " << instance_id << std::endl;
        
        // ========================================
        // 6. 启动心跳线程
        // ========================================
        std::cout << "\n[Step 6] Starting heartbeat thread..." << std::endl;
        
        std::thread heartbeat_thread([&]() {
            std::cout << "  [Heartbeat] Thread started" << std::endl;
            while (g_running) {
                if (registry.heartbeat(instance_id)) {
                    // 静默成功
                } else {
                    std::cerr << "  [Heartbeat] Failed" << std::endl;
                }
                std::this_thread::sleep_for(std::chrono::seconds(10));
            }
            std::cout << "  [Heartbeat] Thread stopped" << std::endl;
        });
        std::cout << "  ✓ Heartbeat thread started (10s interval)" << std::endl;
        
        // ========================================
        // 7. 设置信号处理
        // ========================================
        signal(SIGTERM, signal_handler);
        signal(SIGINT, signal_handler);
        
        std::cout << "\n========================================" << std::endl;
        std::cout << "✅ PingService is running!" << std::endl;
        std::cout << "========================================" << std::endl;
        std::cout << "Service Name:  " << instance.service_name << std::endl;
        std::cout << "Instance ID:   " << instance_id << std::endl;
        std::cout << "gRPC Endpoint: " << host << ":" << port << std::endl;
        std::cout << "========================================" << std::endl;
        std::cout << "Press Ctrl+C to stop..." << std::endl;
        std::cout << std::endl;
        
        // ========================================
        // 8. 主循环
        // ========================================
        while (g_running) {
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
        
        // ========================================
        // 9. 优雅关闭
        // ========================================
        std::cout << "\n========================================" << std::endl;
        std::cout << "[Shutdown] Shutting down gracefully..." << std::endl;
        std::cout << "========================================" << std::endl;
        
        // 注销服务
        std::cout << "[1] Unregistering service..." << std::endl;
        registry.unregister_service(instance_id);
        std::cout << "  ✓ Service unregistered" << std::endl;
        
        // 停止心跳线程
        std::cout << "[2] Stopping heartbeat thread..." << std::endl;
        if (heartbeat_thread.joinable()) {
            heartbeat_thread.join();
        }
        std::cout << "  ✓ Heartbeat thread stopped" << std::endl;
        
        // 停止gRPC服务器
        std::cout << "[3] Stopping gRPC server..." << std::endl;
        server.stop();
        std::cout << "  ✓ gRPC server stopped" << std::endl;
        
        // 停止业务服务
        std::cout << "[4] Stopping PingService..." << std::endl;
        ping_service->Stop();
        std::cout << "  ✓ PingService stopped" << std::endl;
        
        std::cout << "\n========================================" << std::endl;
        std::cout << "✅ PingService shutdown complete" << std::endl;
        std::cout << "========================================" << std::endl;
        
        return 0;
        
    } catch (const std::exception& e) {
        std::cerr << "\n❌ Fatal error: " << e.what() << std::endl;
        return 1;
    }
}
